package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.filePath}")
    private String filePath;
    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //获取原始的文件名
        String fileName = UUID.randomUUID().toString();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        fileName = fileName+suffixName;
        file.transferTo(new File(filePath+fileName));
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param response
     * @param name
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response ,String name){
        try {
            response.setContentType("image/jpeg");
            FileInputStream fileInputStream = new FileInputStream(new File(filePath, name));
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
